/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package bt;

import java.io.*;
import java.util.Vector;
import javax.bluetooth.*;

/**
 *
 * @author kszyh
 */
public class BTServer {

    private BluetoothConnection[] btConnection;
    private boolean isServer;
    private Vector consoleStrings = new Vector();


    public BTServer(BluetoothConnection[] btConns, boolean _isServer) {
        isServer = _isServer;
        btConnection = btConns;

        for (int i = 0; i < btConnection.length; i++) {
            ReceiveThread rt = new ReceiveThread(i);
            rt.start();
        }
    }

    public BluetoothConnection getConnection(int id) {
        return btConnection[id];
    }

    private synchronized void close() {
        for (int i = 0; i < btConnection.length; i++) {
            btConnection[i].close();
        }
    }


    public void updateRemoteChar(int id, String c) {
        if(true == isServer){
        for (int i = 0; i < btConnection.length; i++) {
                sendIntegerToPeer(i, (String) c);
            System.out.println("Przeslano: " + c);
        }
        }
       
        Main.form1.rozmowaIncoming(Integer.toString(id) +": ", c);

    }

    private void sendIntegerToPeer(int peerIndex, String c) {
        BluetoothConnection connection = btConnection[peerIndex];

        try {
            connection.writeString(c); //wysyla ?
        } catch (IOException ex) {
            System.out.println("Bład! Zamykam połączenie.");
            connection.close();
        }
    }

    public void send(String liczba){
    if(true == isServer){
    for(int i = 0; i<btConnection.length; i++)
    sendIntegerToPeer(i,liczba);
    //Main.form1.rozmowaIncoming("Nadawca: ", liczba);
    } else {
    sendIntegerToPeer(0,liczba);
    //Main.form1.rozmowaIncoming("Nadawca_2: ", liczba);
    }
    Main.form1.rozmowaOutcoming(liczba);        // zapis rozmowy wychodzącej
    }

    private class ReceiveThread extends Thread {

        private int index;

        public ReceiveThread(int i) {
            index = i;
        }

        @Override
        public void run() {
            String inp;
            while (true) {
                try {
                    inp = getConnection(index).readString();
                } catch (IOException e) {
                    System.out.println("Bład! Nie udało się uruchomić wątku.");
                    getConnection(index).close();
                    return;
                }

                /*if (inp == -1) {
                getConnection(index).close();
                return;
                }*/
                
                updateRemoteChar(index, inp);
            }
        }
    }
}

